package com.grayscale.dashboard.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.grayscale.core.adapt.GrayScaleRuleAdapt;
import com.grayscale.core.config.GrayScaleZookeeper;
import com.grayscale.core.constant.GrayScaleConstants;
import com.grayscale.core.factory.GrayScaleRuleFactory;
import com.grayscale.core.util.GrayScalePathBuilder;
import com.grayscale.dashboard.service.FunctionRuleService;
import com.grayscale.dashboard.util.StringUtils;
import com.grayscale.core.entity.InterfaceRuleVo;
import com.grayscale.dashboard.web.base.AjaxResult;
import com.grayscale.dashboard.web.base.BaseService;
import com.grayscale.dashboard.web.page.PageDomain;
import com.grayscale.dashboard.web.page.TableDataInfo;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * @author liuli
 * @date 2022/2/22
 */
@Service
public class FunctionRuleServiceImpl extends BaseService implements FunctionRuleService {
    @Resource
    GrayScaleZookeeper grayScaleZookeeper;

    @Override
    public TableDataInfo getInterfaceRule(InterfaceRuleVo interfaceRuleVo, PageDomain pageDomain) {
        List<InterfaceRuleVo> originalList = getInterfaceRuleVos(interfaceRuleVo);
        TableDataInfo rspData = new TableDataInfo();
        if (originalList == null || originalList.size() <=0 ){
            rspData.setRows(new ArrayList<>());
            rspData.setTotal(0);
            return rspData;
        }
        //查询条件过滤
        List<InterfaceRuleVo> list = new ArrayList<>();
        if (StringUtils.isNotBlank(interfaceRuleVo.getRuleCode())){
            for (int i = 0; i < originalList.size(); i++) {
                if (originalList.get(i).getRuleCode().contains(interfaceRuleVo.getRuleCode())){
                    list.add(originalList.get(i));
                }
            }
            if (list == null || list.size() <=0){
                rspData.setRows(list);
                rspData.setTotal(0);
                return rspData;
            }
        }else{
            list = originalList;
        }
        int fromIndex=(pageDomain.getPageNum()-1)*pageDomain.getPageSize();
        int toIndex =fromIndex+pageDomain.getPageSize();
        if (fromIndex>list.size()){
            fromIndex =0;
            toIndex = 0;
        }else if(list.size() <= toIndex){
            toIndex = list.size();
        }
        List<InterfaceRuleVo> pageList = list.subList(fromIndex,toIndex);
        rspData.setRows(pageList);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }



    @Override
    public String getParameter(String appCode, String interfaceCode) {
        return grayScaleZookeeper.getPathData(GrayScalePathBuilder.buildGrayScaleRootPath()+"/"+appCode+GrayScaleConstants.SERVER+"/"+interfaceCode+GrayScaleConstants.PARAMETERS);
    }

    @Override
    public AjaxResult addRule(InterfaceRuleVo interfaceRuleVo) {
        //同一种类型的可以配置多个
        try {
            GrayScaleRuleAdapt grayScaleRuleAdapt = GrayScaleRuleFactory.getDealClass(interfaceRuleVo.getRuleCode());
            if (!grayScaleRuleAdapt.check(interfaceRuleVo.getRuleValue())){
                return  AjaxResult.error("参数格式错误");
            }
        } catch (Exception e) {
            return  AjaxResult.error("规则尚未完成");
        }
        interfaceRuleVo.setId(System.currentTimeMillis());
        interfaceRuleVo.setCreatedTime(new Date());
        interfaceRuleVo.setUpdateTime(new Date());
        List<InterfaceRuleVo> originalList = getInterfaceRuleVos(interfaceRuleVo);
        if (originalList == null || originalList.size() <=0){
            //没有直接添加
            originalList = new ArrayList<>();
            originalList.add(interfaceRuleVo);
        }else{
            originalList.add(interfaceRuleVo);
        }
        saveRule(interfaceRuleVo, JSONObject.toJSONString(originalList));
        return AjaxResult.success();
    }

    @Override
    public InterfaceRuleVo getInterfaceRuleById(String appCode,String interfaceCode, Long id) {
        InterfaceRuleVo interfaceRuleVo = new InterfaceRuleVo();
        interfaceRuleVo.setAppCode(appCode);
        interfaceRuleVo.setInterfaceCode(interfaceCode);
        List<InterfaceRuleVo> originalList = getInterfaceRuleVos(interfaceRuleVo);
        Iterator<InterfaceRuleVo> iterator = originalList.iterator();
        //移除该记录
        while (iterator.hasNext()){
            InterfaceRuleVo next = iterator.next();
            if (next.getId().equals(id)){
               return  next;
            }
        }
        return null;
    }

    @Override
    public AjaxResult remove(InterfaceRuleVo interfaceRuleVo) {
        List<InterfaceRuleVo> originalList = getInterfaceRuleVos(interfaceRuleVo);
        Iterator<InterfaceRuleVo> iterator = originalList.iterator();
        //移除该记录
        while (iterator.hasNext()){
            InterfaceRuleVo next = iterator.next();
            if (next.getId().equals(interfaceRuleVo.getId())){
                iterator.remove();
            }
        }
        //更新规则
        saveRule(interfaceRuleVo, JSONObject.toJSONString(originalList));
        return AjaxResult.success();
    }

    @Override
    public AjaxResult editRule(InterfaceRuleVo interfaceRuleVo) {
        InterfaceRuleVo oldInterfaceRuleVo = getInterfaceRuleById(interfaceRuleVo.getAppCode(),interfaceRuleVo.getInterfaceCode(),interfaceRuleVo.getId());
        if (oldInterfaceRuleVo == null){
            return AjaxResult.error("该规则已经删除");
        }
        try {
            GrayScaleRuleAdapt grayScaleRuleAdapt = GrayScaleRuleFactory.getDealClass(interfaceRuleVo.getRuleCode());
            if (!grayScaleRuleAdapt.check(interfaceRuleVo.getRuleValue())){
                return  AjaxResult.error("参数格式错误");
            }
        } catch (Exception e) {
            return  AjaxResult.error("规则尚未完成");
        }
        List<InterfaceRuleVo> originalList = getInterfaceRuleVos(interfaceRuleVo);
        Iterator<InterfaceRuleVo> iterator = originalList.iterator();
        //移除该记录
        while (iterator.hasNext()){
            InterfaceRuleVo next = iterator.next();
            if (next.getId().equals(interfaceRuleVo.getId())){
                next.setRuleValue(interfaceRuleVo.getRuleValue());
                next.setUpdateTime(new Date());
            }
        }
        saveRule(interfaceRuleVo, JSONObject.toJSONString(originalList));
        return AjaxResult.success();
    }

    private void saveRule(InterfaceRuleVo interfaceRuleVo,String data){
        grayScaleZookeeper.setPathData(GrayScalePathBuilder.buildGrayScaleRootPath()+"/"+interfaceRuleVo.getAppCode()+GrayScaleConstants.SERVER+"/"+interfaceRuleVo.getInterfaceCode()+ GrayScaleConstants.RULES,data);
    };


    private List<InterfaceRuleVo> getInterfaceRuleVos(InterfaceRuleVo interfaceRuleVo) {
        String pathData = grayScaleZookeeper.getPathData(GrayScalePathBuilder.buildGrayScaleRootPath()+"/"+ interfaceRuleVo.getAppCode()+GrayScaleConstants.SERVER+"/"+ interfaceRuleVo.getInterfaceCode()+GrayScaleConstants.RULES);
        if (StringUtils.isBlank(pathData)){
            return null;
        }
        List<InterfaceRuleVo>  originalList = JSONObject.parseArray(pathData,InterfaceRuleVo.class);
        return originalList;
    }
}
